package com.mobiusws.reports.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.mobiusws.reports.action.DailyFraudSummaryAction;
import com.mobiusws.reports.model.CallType;
import com.mobiusws.reports.model.DailyFraudSummary;
import com.mobiusws.reports.model.LoginInfo;
import com.mobiusws.util.JsonUtil;
import com.mobiusws.util.SqlUtil;

@Repository("dailyFraudSummaryDao")
public class DailyFraudSummaryDao {
	@Resource
	private JdbcTemplate dbxJdbc;
	@Resource
	private JdbcTemplate coreJdbc;
	@Resource
	private SqlUtil sqlUtil;
	private Logger logger = Logger.getRootLogger();

	private int cnt;
	private List<?> list;

	private void logStmt(String sql, Object[] param) {
		logger.info(sql);
		StringBuilder logTxtBld = new StringBuilder();
		for (Object para : param) {
			logTxtBld.append(para).append(", ");
		}
		logger.info(logTxtBld.substring(0, logTxtBld.length() - 2));
	}

	private void execQuery(JdbcTemplate jdbc, String sql, Object[] param,
			BeanPropertyRowMapper rowMapper, QueryType queryType) {
		logStmt(sql, param);
		switch (queryType) {
		case INT:
			this.cnt = jdbc.queryForInt(sql, param);
			break;
		case LIST:
			this.list = jdbc.query(sql, param, rowMapper);
			break;
		}
	}

	public List<DailyFraudSummary> getDailyFraudSummary(
			DailyFraudSummaryAction action) {
		if (action.getStart() == 0 || action.getTotal() < 1) {
			String sqlCnt = sqlUtil
					.getSqlById("getDailyFraudSummaryByDayCount");
			Object[] param = new Object[] { action.getSelDate() };
			execQuery(dbxJdbc, sqlCnt, param, null, QueryType.INT);
			action.setTotal(cnt);
		}
		if (action.getTotal() > 0) {
			String sql = sqlUtil.getSqlById("getDailyFraudSummaryByDay");
			Object[] params = new Object[] { action.getSelDate(),
					action.getStart(), action.getLimit() };
			BeanPropertyRowMapper rowMapper = new BeanPropertyRowMapper(
					DailyFraudSummary.class);
			execQuery(dbxJdbc, sql, params, rowMapper, QueryType.LIST);
		} else {
			this.list = new ArrayList();
		}
		return (List<DailyFraudSummary>) this.list;
	}
}
